import { defineStore } from 'pinia'
import { userAPI } from '@/api'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    user: null,
    isLoggedIn: false
  }),
  
  getters: {
    isAuthenticated: (state) => !!state.token && state.isLoggedIn
  },
  
  actions: {
    // 登录
    async login(credentials) {
      try {
        const response = await userAPI.login(credentials)
        // 根据后端返回格式：{ code: 2000, message: "操作成功", data: "jwt_token" }
        if (response.code === 2000) {
          this.token = response.data
          this.isLoggedIn = true
          
          // 解析JWT token获取用户信息（可选）
          try {
            const payload = JSON.parse(atob(response.data.split('.')[1]))
            this.user = {
              id: payload.sub,
              name: payload['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name'],
              email: payload['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress'],
              role: payload['http://schemas.microsoft.com/ws/2008/06/identity/claims/role']
            }
            
            // 权限验证：检查用户是否为管理员
            const userRole = this.user.role
            if (!userRole || (userRole !== 'Admin' && userRole !== 'Administrator' && userRole !== '管理员')) {
              // 清除已设置的登录状态
              this.token = ''
              this.user = null
              this.isLoggedIn = false
              localStorage.removeItem('token')
              throw new Error('权限不足，只有管理员可以登录此系统')
            }
          } catch (e) {
            if (e.message.includes('权限不足')) {
              throw e // 重新抛出权限错误
            }
            console.warn('Failed to parse JWT token:', e)
          }
          
          // 保存token到localStorage
          localStorage.setItem('token', this.token)
          
          return response
        } else {
          throw new Error(response.message || '登录失败')
        }
      } catch (error) {
        throw error
      }
    },
    
    // 登出
    logout() {
      this.token = ''
      this.user = null
      this.isLoggedIn = false
      localStorage.removeItem('token')
    },
    
    // 初始化认证状态
    initAuth() {
      const token = localStorage.getItem('token')
      if (token) {
        this.token = token
        this.isLoggedIn = true
        // 这里可以添加验证token有效性的逻辑
      }
    }
  }
})